import { GameConfig } from '../config/GameConfig.js';

export class UISystem {
    private selectedWeapon: string | null = null;
    private gameState: {
        money: number;
        interceptRate: number;
        currentWave: number;
        buildingHealth: number;
        threatLevel: string;
    };
    
    // 事件回调
    public onWeaponSelect: ((weaponType: string) => void) | null = null;
    public onBuildDefenseSystem: ((weaponType: string, gridX: number, gridY: number) => boolean) | null = null;

    constructor() {
        this.gameState = {
            money: GameConfig.INITIAL_MONEY,
            interceptRate: 0,
            currentWave: GameConfig.INITIAL_WAVE,
            buildingHealth: 100,
            threatLevel: '低'
        };
    }

    async init(): Promise<void> {
        console.log('🖥️ 初始化UI系统...');
        this.setupWeaponSelection();
        this.setupDefenseGrid();
        this.updateUI();
        console.log('✅ UI系统初始化完成');
    }

    update(deltaTime: number): void {
        // UI系统的更新逻辑
        this.updateUI();
    }

    private setupWeaponSelection(): void {
        const weaponButtons = document.querySelectorAll('.weapon-btn');
        
        weaponButtons.forEach(button => {
            button.addEventListener('click', (event) => {
                const weaponType = (event.currentTarget as HTMLElement).getAttribute('data-weapon');
                if (weaponType) {
                    this.selectWeapon(weaponType);
                }
            });
        });
    }

    private setupDefenseGrid(): void {
        const defenseArea = document.getElementById('defenseArea');
        if (!defenseArea) return;

        // 清空现有网格
        defenseArea.innerHTML = '';

        // 创建防御网格
        for (let row = 0; row < GameConfig.DEFENSE_GRID_ROWS; row++) {
            for (let col = 0; col < GameConfig.DEFENSE_GRID_COLS; col++) {
                const gridCell = document.createElement('div');
                gridCell.className = 'defense-grid';
                gridCell.style.position = 'absolute';
                gridCell.style.left = `${col * GameConfig.DEFENSE_GRID_SIZE}px`;
                gridCell.style.top = `${row * GameConfig.DEFENSE_GRID_SIZE}px`;
                gridCell.style.width = `${GameConfig.DEFENSE_GRID_SIZE}px`;
                gridCell.style.height = `${GameConfig.DEFENSE_GRID_SIZE}px`;
                gridCell.setAttribute('data-grid-x', col.toString());
                gridCell.setAttribute('data-grid-y', row.toString());

                // 添加鼠标悬停效果
                gridCell.addEventListener('mouseenter', () => {
                    if (!gridCell.classList.contains('occupied') && this.selectedWeapon) {
                        gridCell.classList.add('selected');
                    }
                });

                gridCell.addEventListener('mouseleave', () => {
                    gridCell.classList.remove('selected');
                });

                // 添加点击事件
                gridCell.addEventListener('click', (event) => {
                    event.stopPropagation();
                    this.handleGridClick(col, row, gridCell);
                });

                defenseArea.appendChild(gridCell);
            }
        }
    }

    private handleGridClick(gridX: number, gridY: number, gridElement: HTMLElement): void {
        if (!this.selectedWeapon) {
            console.log('⚠️ 请先选择要建造的武器系统');
            return;
        }

        if (gridElement.classList.contains('occupied')) {
            console.log('❌ 该位置已被占用');
            return;
        }

        // 检查是否有足够资金
        const weaponCost = this.getWeaponCost(this.selectedWeapon);
        if (this.gameState.money < weaponCost) {
            console.log('💰 资金不足');
            this.showMessage('资金不足！', 'error');
            return;
        }

        console.log(`🏗️ 在网格 (${gridX}, ${gridY}) 建造 ${this.selectedWeapon}`);
        
        // 🔧 调用GameEngine进行实际建造
        if (this.onBuildDefenseSystem) {
            const success = this.onBuildDefenseSystem(this.selectedWeapon, gridX, gridY);
            if (success) {
                // 只有建造成功才扣除资金和更新UI
                this.gameState.money -= weaponCost;
                this.occupyGrid(gridX, gridY, gridElement);
                this.updateUI();
                this.showMessage(`${this.getWeaponName(this.selectedWeapon)} 建造成功！`, 'success');
            } else {
                console.log('❌ 建造失败');
                this.showMessage('建造失败！', 'error');
            }
        } else {
            console.error('❌ 建造回调函数未设置！');
        }
    }

    private selectWeapon(weaponType: string): void {
        // 清除之前的选择
        document.querySelectorAll('.weapon-btn').forEach(btn => {
            btn.classList.remove('selected');
        });

        // 选择新武器
        const selectedButton = document.querySelector(`[data-weapon="${weaponType}"]`);
        if (selectedButton) {
            selectedButton.classList.add('selected');
            this.selectedWeapon = weaponType;
            console.log(`🔫 选择武器: ${this.getWeaponName(weaponType)}`);
            
            if (this.onWeaponSelect) {
                this.onWeaponSelect(weaponType);
            }
        }
    }

    private occupyGrid(gridX: number, gridY: number, gridElement: HTMLElement): void {
        gridElement.classList.add('occupied');
        gridElement.classList.remove('selected');
        
        // 创建武器显示容器
        const weaponDisplay = document.createElement('div');
        weaponDisplay.style.width = '100%';
        weaponDisplay.style.height = '100%';
        weaponDisplay.style.display = 'flex';
        weaponDisplay.style.alignItems = 'center';
        weaponDisplay.style.justifyContent = 'center';
        weaponDisplay.style.position = 'relative';
        
        // 首先尝试显示SVG图标
        this.createWeaponSVGDisplay(weaponDisplay, this.selectedWeapon!);
        
        gridElement.appendChild(weaponDisplay);
    }
    
    private async createWeaponSVGDisplay(container: HTMLElement, weaponType: string): Promise<void> {
        try {
            // 创建SVG图片元素
            const svgElement = document.createElement('img');
            svgElement.style.width = '32px';
            svgElement.style.height = '32px';
            svgElement.style.filter = 'drop-shadow(0 2px 4px rgba(0,0,0,0.3))';
            
            // 根据武器类型设置SVG路径
            let svgPath = '';
            switch (weaponType) {
                case 'iron-dome':
                    svgPath = '/svg/weapons/israeli/iron-dome.svg';
                    break;
                case 'arrow-3':
                    svgPath = '/svg/weapons/israeli/arrow-3.svg';
                    break;
                case 'green-pine-radar':
                    svgPath = '/svg/weapons/israeli/green-pine-radar.svg';
                    break;
                default:
                    throw new Error('Unknown weapon type');
            }
            
            // 设置SVG源并添加错误处理
            svgElement.src = svgPath;
            svgElement.onerror = () => {
                // SVG加载失败时，回退到几何图形显示
                console.warn(`SVG加载失败: ${svgPath}, 使用备用显示`);
                this.createFallbackDisplay(container, weaponType);
            };
            
            svgElement.onload = () => {
                console.log(`✅ SVG加载成功: ${svgPath}`);
            };
            
            container.appendChild(svgElement);
            
        } catch (error) {
            console.warn('SVG显示失败，使用备用方案:', error);
            this.createFallbackDisplay(container, weaponType);
        }
    }
    
    private createFallbackDisplay(container: HTMLElement, weaponType: string): void {
        // 清空容器
        container.innerHTML = '';
        
        // 创建几何图形背景
        const shape = document.createElement('div');
        shape.style.width = '30px';
        shape.style.height = '30px';
        shape.style.borderRadius = '50%';
        shape.style.border = '2px solid #ffffff';
        shape.style.position = 'relative';
        shape.style.display = 'flex';
        shape.style.alignItems = 'center';
        shape.style.justifyContent = 'center';
        
        // 根据武器类型设置颜色和样式
        const weaponStyle = this.getWeaponStyle(weaponType);
        shape.style.backgroundColor = weaponStyle.color;
        
        // 添加武器标识
        const label = document.createElement('span');
        label.style.color = 'white';
        label.style.fontWeight = 'bold';
        label.style.fontSize = '12px';
        label.textContent = weaponStyle.label;
        
        shape.appendChild(label);
        container.appendChild(shape);
    }

    private updateUI(): void {
        // 更新顶部信息栏
        this.updateElement('money', this.formatMoney(this.gameState.money));
        this.updateElement('interceptRate', `${this.gameState.interceptRate}%`);
        this.updateElement('waveInfo', `${this.gameState.currentWave}/${GameConfig.MAX_WAVES}`);
        this.updateElement('buildingHealth', `${this.gameState.buildingHealth}%`);
        this.updateElement('threatLevel', this.gameState.threatLevel);

        // 更新武器按钮的可用性
        this.updateWeaponButtons();
    }

    private updateElement(id: string, value: string): void {
        const element = document.getElementById(id);
        if (element) {
            element.textContent = value;
        }
    }

    private updateWeaponButtons(): void {
        document.querySelectorAll('.weapon-btn').forEach(button => {
            const weaponType = button.getAttribute('data-weapon');
            if (weaponType) {
                const cost = this.getWeaponCost(weaponType);
                const canAfford = this.gameState.money >= cost;
                
                button.classList.toggle('disabled', !canAfford);
                if (canAfford) {
                    button.removeAttribute('disabled');
                } else {
                    button.setAttribute('disabled', 'true');
                }
            }
        });
    }

    private getWeaponCost(weaponType: string): number {
        switch (weaponType) {
            case 'iron-dome':
                return GameConfig.DEFENSE_SYSTEMS.IRON_DOME.cost;
            case 'arrow-3':
                return GameConfig.DEFENSE_SYSTEMS.ARROW_3.cost;
            case 'green-pine-radar':
                return GameConfig.DEFENSE_SYSTEMS.GREEN_PINE_RADAR.cost;
            default:
                return 0;
        }
    }

    private getWeaponName(weaponType: string): string {
        switch (weaponType) {
            case 'iron-dome':
                return GameConfig.DEFENSE_SYSTEMS.IRON_DOME.name;
            case 'arrow-3':
                return GameConfig.DEFENSE_SYSTEMS.ARROW_3.name;
            case 'green-pine-radar':
                return GameConfig.DEFENSE_SYSTEMS.GREEN_PINE_RADAR.name;
            default:
                return '未知武器';
        }
    }

    private getWeaponIcon(weaponType: string): string {
        // 不再使用emoji，而是返回几何图形描述
        switch (weaponType) {
            case 'iron-dome':
                return 'ID'; // Iron Dome abbreviation
            case 'arrow-3':
                return 'A3'; // Arrow-3 abbreviation  
            case 'green-pine-radar':
                return 'GP'; // Green Pine abbreviation
            default:
                return '?';
        }
    }

    private getWeaponStyle(weaponType: string): { color: string; label: string } {
        switch (weaponType) {
            case 'iron-dome':
                return { color: '#2E86AB', label: 'ID' };
            case 'arrow-3':
                return { color: '#A23B72', label: 'A3' };
            case 'green-pine-radar':
                return { color: '#F18F01', label: 'GP' };
            default:
                return { color: '#666666', label: '?' };
        }
    }

    private formatMoney(amount: number): string {
        if (amount >= 1000000) {
            return `${(amount / 1000000).toFixed(1)}M`;
        } else if (amount >= 1000) {
            return `${(amount / 1000).toFixed(0)}K`;
        } else {
            return amount.toString();
        }
    }

    private showMessage(message: string, type: 'success' | 'error' | 'warning' | 'info' = 'info'): void {
        // 创建消息元素
        const messageElement = document.createElement('div');
        messageElement.style.position = 'fixed';
        messageElement.style.top = '100px';
        messageElement.style.left = '50%';
        messageElement.style.transform = 'translateX(-50%)';
        messageElement.style.padding = '10px 20px';
        messageElement.style.borderRadius = '5px';
        messageElement.style.color = 'white';
        messageElement.style.fontWeight = 'bold';
        messageElement.style.zIndex = '1000';
        messageElement.style.opacity = '0';
        messageElement.style.transition = 'opacity 0.3s';
        messageElement.textContent = message;

        // 设置颜色
        switch (type) {
            case 'success':
                messageElement.style.backgroundColor = GameConfig.COLORS.SUCCESS;
                break;
            case 'error':
                messageElement.style.backgroundColor = GameConfig.COLORS.DANGER;
                break;
            case 'warning':
                messageElement.style.backgroundColor = GameConfig.COLORS.WARNING;
                break;
            default:
                messageElement.style.backgroundColor = GameConfig.COLORS.INFO;
        }

        document.body.appendChild(messageElement);

        // 显示动画
        setTimeout(() => {
            messageElement.style.opacity = '1';
        }, 10);

        // 自动移除
        setTimeout(() => {
            messageElement.style.opacity = '0';
            setTimeout(() => {
                if (messageElement.parentNode) {
                    messageElement.parentNode.removeChild(messageElement);
                }
            }, 300);
        }, 2000);
    }

    // 公共接口
    public getSelectedWeapon(): string | null {
        return this.selectedWeapon;
    }

    public setSelectedWeapon(weaponType: string): void {
        this.selectWeapon(weaponType);
    }

    public updateMoney(amount: number): void {
        this.gameState.money = amount;
        this.updateUI();
    }

    public updateInterceptRate(rate: number): void {
        this.gameState.interceptRate = Math.round(rate);
        this.updateUI();
    }

    public updateWave(wave: number): void {
        this.gameState.currentWave = wave;
        this.updateUI();
    }

    public updateBuildingHealth(health: number): void {
        this.gameState.buildingHealth = Math.round(health);
        this.updateUI();
    }

    public updateThreatLevel(level: string): void {
        this.gameState.threatLevel = level;
        this.updateUI();
    }

    public updateGridDisplay(gridX: number, gridY: number, occupied: boolean): void {
        const gridElement = document.querySelector(`[data-grid-x="${gridX}"][data-grid-y="${gridY}"]`) as HTMLElement;
        if (gridElement) {
            if (occupied) {
                this.occupyGrid(gridX, gridY, gridElement);
            } else {
                gridElement.classList.remove('occupied');
                gridElement.innerHTML = '';
            }
        }
    }

    public getGameState() {
        return { ...this.gameState };
    }

    // 更新游戏状态面板
    public updateGameStatus(activeMissiles: number, defenseSystems: number, currentWave: number, gameState: string): void {
        this.updateElement('activeMissiles', activeMissiles.toString());
        this.updateElement('defenseSystems', defenseSystems.toString());
        this.updateElement('currentWave', currentWave.toString());
        this.updateElement('gameState', gameState);
    }
}
